package com.netx.cubigraf.entities;
import com.netx.generics.basic.Checker;
import com.netx.generics.basic.IntegrityException;
import com.netx.generics.time.Date;
import com.netx.generics.sql.Table;
import com.netx.data.Entity;
import com.netx.data.Connection;
import com.netx.data.ValueList;
import com.netx.data.DatabaseException;


public class ComprasPelicula extends Entity {

	public ComprasPelicula() {
		super();
	}
	
	public void inserirCompra(Date data, long tipoRolo) throws DatabaseException {
		ValueList values = new ValueList();
		values.addValue("ano", data.getYear());
		values.addValue("mes", data.getMonth());
		values.addValue("tipo_rolo", tipoRolo);
		final Connection c = getConnection();
		final GestaoPelicula gp = Entities.getGestaoPelicula(c);
		synchronized(c) {
			startTransaction();
			insert(values);
			int result = gp.actualizarLinha(data, this);
			if(result != 1) {
				throw new IntegrityException(result);
			}
			commit();
		}
	}
	
	public void apagarCompra(Date data, long compraPeliculaID) throws DatabaseException {
		int result = delete(compraPeliculaID);
		if(result != 1) {
			throw new IntegrityException(result);
		}
		Entities.getGestaoPelicula(getConnection()).actualizarLinha(data, this);
	}

	public Table verComprasPelicula(Date data) throws DatabaseException {
		Checker.checkNull(data, "data");
		return getConnection().select("cp.compras_pelicula_id, cp.reg_date, cp.tipo_rolo, tr.largura, tr.comprimento from tipos_rolo tr, compras_pelicula cp where cp.ano="+data.getYear()+" and cp.mes="+data.getMonth()+" and cp.tipo_rolo=tr.tipo_rolo_id order by cp.compras_pelicula_id");
	}

	// For GestaoPelicula.actualizarLinha:
	Table verAreaComprada(Date data) throws DatabaseException {
		Checker.checkNull(data, "data");
		return getConnection().select("sum(tr.largura * tr.comprimento) from tipos_rolo tr, compras_pelicula cp where cp.ano="+data.getYear()+" and cp.mes="+data.getMonth()+" and cp.tipo_rolo=tr.tipo_rolo_id");
	}
	
	public void zerar() throws DatabaseException {
		this.delete("1=1");
	}
}
